package com.york.aclservice.service.impl;

import com.york.aclservice.entity.User;
import com.york.aclservice.service.PermissionService;
import com.york.aclservice.service.UserService;
import com.york.security.entity.CurrentUserInfo;
import com.york.security.entity.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Data: 2022/3/22 20:25
 * @Author: yangboxiong
 * @Version
 * @since JDK 1.8
 */
@Service("userDetailsService")      //需要跟核心配置类中的 userDetailsService的实例对象名一样
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询数据
        User user = userService.selectByUsername(username);
        //判断
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //Spring Security 的实体类名一样
        CurrentUserInfo curCurrentUserInfo = new CurrentUserInfo();
        //将当前的user对象，拷贝到Spring Security 中去
        BeanUtils.copyProperties(user, curCurrentUserInfo);

        //根据当前用户查询用户权限列表
        List<String> permissionValueList = permissionService.selectPermissionValueByUserId(user.getId());
        SecurityUser securityUser = new SecurityUser();
        //当前登录用户
        securityUser.setCurrentUserInfo(curCurrentUserInfo);
        //当前权限
        securityUser.setPermissionValueList(permissionValueList);
        return securityUser;
    }
}
